<template>
  <el-dialog :visible.sync="dialogVisible" width="600px" :before-close="close"
             :title="type?'添加超大附件':'添加附件'" center>
    <!--空选情况下-->
    <div class="box" v-if="fileList.length==0">
      <div class="local-btn">
        <el-button type="primary" @click="uploadFile" size="small">上传新文件</el-button>
      </div>
      <p class="drop-zoom"  @dragover="dragover_handler($event)" @drop="drop_handler($event)">将文件拖拽至此区域</p>
    </div>
    <!-- 文件列表展示-->
    <div class="box-file" v-else>
      <!--      选择区域-->
      <div class="top">
        <el-button type="primary" @click="uploadFile" size="small">上传新文件</el-button>
        <span>或拖拽文件到下框</span>
      </div>
      <ul  @dragover="dragover_handler($event)" @drop="drop_handler($event)">
        <li v-for="item,index in fileList">
          <img src="../../../../public/img/email/icon/image.gif" alt="" v-if="filterType(item.name)===1">
          <img v-else-if="filterType(item.name)==2" src="../../../../public/img/video.png" alt="">
          <svg style="flex: 0 0 30px;font-size:33px" v-else class="icon" aria-hidden="true" >
            <use :xlink:href="`#${filterType(item.name)}`"></use>
          </svg>
          <div class="desc">
            <h1 class="more" :title="item.name"><span>{{item.name}}</span> ({{dealSize(item.size)}})</h1>
            <p>
              <span class="error" v-if="item.size>maxSize||(type&&bigLong+index>4)">
                {{item.size>maxSize?('文件大小超出限制，无法上传!'+(type?'(最大300M)':'(最大20M)')):'数量超出限制(最多五个)'}}
              </span>
              <el-progress v-else-if="item.percent!=100&&item.percent!=0" size="mini" :stroke-width="2"
                           :percentage="item.percent" style="width: 250px;"></el-progress>
              <span v-else-if="item.percent==100">完成</span>
            </p>
            <i class="iconfont icon-shanchu1" v-if="(type&&index>4)||(type&&bigLong+index>4)||(item.size>maxSize)" @click="fileList.splice(index,1)"></i>
            <i class="iconfont icon-xuanzhong" v-else-if="item.percent==100"></i>
          </div>
        </li>
      </ul>
    </div>
    <!-- 底部按钮-->
    <div slot="footer" class="dialog-footer" align="right">
      <el-button @click="close" size="mini">取 消</el-button>
      <el-button type="primary" size="mini" @click="submit">确 定</el-button>
    </div>
    <!--    文件选择-->
    <input type="file" @change="onChange" ref="fileTarget" multiple hidden>
  </el-dialog>
</template>

<script>
    import {mapState} from 'vuex'
    import {uploadOss} from '@/util/file'
    import {fileTypeStr, formatTimeThree} from '@/util/util'
    export default {
        name: "DialogFileUpload",
        data() {
            return {
                dialogVisible: false,
                type: 0,
                fileList: [],
                maxSize: 0,
                upList:[],//上传成功的列表
                contentStr:'',//超大附件 - 生成的文本内容
                bigLong:0,//已有的超大附件个数
            }
        },
        computed: {
            ...mapState(['common']),
            percent () {
                return this.common.percent;　　//需要监听的数据
            }
        },
        watch: {
            percent (newVal, oldVal) {
                const center = JSON.parse(JSON.stringify(this.fileList));
                this.fileList = [];
                for(let item of newVal){
                    for(let item1 of center){
                        if(item.oldName==item1.name){
                            item1.percent=item.percent;
                        }
                    }
                }
                this.fileList = center;
            }
        },
        methods: {
            init(type,bigLong) {
                this.$store.commit('RESET_PERCENT');//防止大文件关闭，请求仍在继续导致的插入 percent
                this.type = type;
                this.bigLong=bigLong;
                this.fileList = [];
                this.upList=[];
                this.contentStr='';
                this.maxSize = type ? 314572800 : 20971520;
                this.dialogVisible = true;
            },
            submit() {
                //清除上传中的文件 - common.percent , this.fileList
                this.$store.commit('RESET_PERCENT');//清空即可
                if(this.percent.length>0) {//存在未完成上传的文件
                    this.$confirm('取消未完成的上传?', '附件', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$emit('dealLocalUpload',this.type,this.upList,this.contentStr)
                        this.dialogVisible = false;
                    }).catch(() => {
                        return;
                    });
                }else{
                    this.$emit('dealLocalUpload',this.type,this.upList,this.contentStr)
                    this.dialogVisible = false;
                }
            },
            uploadFile() {
                this.$refs.fileTarget.dispatchEvent(new MouseEvent('click'))
            },
            //1.本地文件选择结果 - 多个
            onChange(event) {
                const files = event.target.files;
                for (let item of files) {
                    // this.fileList.push(Object.assign(item,{percent:0}));
                    this.fileList.push({
                        size: item.size,
                        name: item.name,
                        percent:0
                    })
                }
                this.beforeUpload(files);//新的上传
            },
            //2.拖拽文件选择结果 - 多个
            drop_handler(e) {
                e.preventDefault();
                e.stopPropagation();
                var df = e.dataTransfer;
                var dropFiles = [];
                if (df.items !== undefined) {
                    // Chrome有items属性，对Chrome的单独处理
                    for (var i = 0; i < df.items.length; i++) {
                        var item = df.items[i];
                        // 用webkitGetAsEntry禁止上传目录
                        if (item.kind === "file" && item.webkitGetAsEntry().isFile) {
                            var file = item.getAsFile();
                            dropFiles.push(file);
                        }
                    }
                } else {
                    for (var i = 0; i < df.files.length; i++) {
                        dropFiles.push(df.files[i]);
                    }
                }
                for (let item of dropFiles) {
                    this.fileList.push({
                        size: item.size,
                        name: item.name,
                        percent:0
                    })
                    // this.fileList.push(Object.assign(item,{percent:0}));
                }
                this.beforeUpload(dropFiles);//新的上传

            },
            dragover_handler(ev) {
                ev.preventDefault();
                ev.dataTransfer.dropEffect = "move"
            },
            //上传之前判断 - 是否需要上传
            beforeUpload(list){
                for(let i=0,len=list.length;i<len;i++){
                    const item = list[i];
                    if(this.type){//超大 上传成功+已有的+上传中
                        console.log(this.upList.length,this.bigLong,this.percent.length,i)
                        if((this.upList.length+this.bigLong+this.percent.length+i<5)
                            &&(item.size<=this.maxSize)){
                            this.upload(item);
                        }
                    }else{
                        if(item.size<=this.maxSize){
                            this.upload(item);
                        }
                    }
                }
            },
            upload(file) {
                uploadOss(file, this.type).then(result => {
                    const params = {
                        fileGuid: result.url,
                        fileSize: file.size,
                        picName: result.oldName,
                    }
                    if(this.fileList.length==0)return;
                    if (result.type == 1) {//超大附件
                        this.contentStr+= fileTypeStr(params, this.bigLong);
                        this.upList.push(Object.assign({}, params, {long: this.bigLong, expire: formatTimeThree()}));
                    } else {//附件
                        this.upList.push(params)
                    }
                }).catch(err => {
                    console.log(err)
                    this.$message({
                        type: "success",
                        message: '文件上传失败,请重新上传!'
                    })
                })
            },
            close(){
                //判断是否存在上传中的文件
                if(this.percent.length>0){//存在未完成上传的文件
                    this.$confirm('取消未完成的上传?', '附件', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //清除上传中的文件 - common.percent , this.fileList
                        this.$store.commit('RESET_PERCENT');//清空即可
                        this.dialogVisible=false;
                    }).catch(() => {return;});
                }else{
                    this.dialogVisible=false;
                }
            },
            //转换文件单位
            dealSize(size) {
                size = size.toString();
                if (size.indexOf('KB') != -1 || size.indexOf('B') != -1 || size.indexOf('MB') != -1) {
                    return size;
                }
                let result = parseInt(size / 1024);
                if (result > 1024) {
                    return parseInt(result / 1024) + 'M';
                }
                return result + 'KB';
            },
            //判断文件类型
            filterType(name) {
                name = name.toLowerCase();
                //截取类型
                let index = name.lastIndexOf(".");
                let fileName = "." + name.substr(index + 1);
                let images = ['.jpg', '.jpeg', '.png', '.gif'];
                let videos = ['.avi', '.mp4', '.wav', '.rm', '.rmvb', '.mov', '.dat', '.wmv', '.3gp', '.amv', '.dmv', '.flv'];
                let files = ['.ppt', '.pptx', '.pdf', '.doc', '.psd', '.txt', '.xls', '.xlsx'];
                //图片判断
                if (images.includes(fileName)) {
                    return 1
                } else if (videos.includes(fileName)) {
                    return 2
                } else if (files.includes(fileName)) {
                    switch (fileName) {
                        case '.ppt':
                            return 'icon-ppt';
                        case '.pptx':
                            return 'icon-ppt';
                        case '.pdf':
                            return 'icon-pdf'
                        case '.doc':
                            return 'icon-doc'
                        case '.psd':
                            return 'icon-psd'
                        case '.txt':
                            return 'icon-txt'
                        case '.xlsx':
                            return 'icon-xlsx'
                        case '.xls':
                            return 'icon-xlsx'
                        default:
                            return 'icon-folder'
                    }
                } else {
                    return 'icon-doc'
                }
            }
        }
    }
</script>

<style scoped lang="scss">
  .box {
    border: 1px solid #f5f5f5;
    text-align: center;

    .local-btn {
      height: 100px;
      line-height: 100px;

      .el-button {
        margin-bottom: 20px;
      }
    }

    .drop-zoom {
      margin: 0 25px !important;
      /*border-top: 1px solid #f5f5f5;*/
      height: 200px;
      line-height: 200px;
      border-top: 1px transparent solid;
      border-image: linear-gradient(to right, #ddd, #666, #ddd) 1 10;
    }
  }

  .box-file {
    .top {
      padding-top: 10px;
      padding-bottom: 20px;

      span {
        margin-left: 30px;
        font-size: 14px;
        color: #666;
      }
    }

    ul {
      height: 278px;
      padding: 5px 0 0 0 !important;
      overflow-y: auto;
      border: 1px solid #ddd;
      border-radius: 10px;

      li {
        display: flex;
        padding: 5px 10px;
        border-bottom: 1px solid #ddd;
        position: relative;

        img {
          width: 32px;
          height: 32px;
        }

        .desc {
          padding: 0 10px;
          width: calc(100% - 40px);
          color: #999;


          h1 {
            font-weight: normal;
            font-size: 12px;
            width: 80%;

            span {
              color: #000;
            }
          }

          p {
            span{
              font-size: 12px;
            }
            .error {
              font-size: 12px;
              color: red;
            }
          }

          i.iconfont {
            position: absolute;
            right: 5px;
            top: 12px;
            font-size: 22px;
            color: lightgreen;
          }

          i.iconfont.icon-shanchu1 {
            color: #ddd;
          }
        }
      }

      li:last-child {
        /*border-bottom: 0;*/
      }

    }
  }
</style>
